package com.zjh.es;

import java.util.concurrent.Flow;
import java.util.concurrent.atomic.AtomicInteger;

public class ReactiveDemo2 {
    static class Processor implements Flow.Processor<String, String> {
        Flow.Subscriber<? super String> downstream;
        @Override
        public void subscribe(Flow.Subscriber<? super String> subscriber) {
                this.downstream=subscriber;
        }

        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            System.out.println("processor handler data");
            subscription.request(1);
        }

        @Override
        public void onNext(String item) {
            System.out.println("downstream受到数据，开始处理数据");
            downstream.onNext(item+"欢迎你");
            downstream.onComplete();
        }

        @Override
        public void onError(Throwable throwable) {
            System.out.println("数据有误");
        }

        @Override
        public void onComplete() {
            System.out.println("downstream数据接收完毕");
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Flow.Publisher<String> publisher = new Flow.Publisher<String>() {
            @Override
            public void subscribe(Flow.Subscriber<? super String> subscriber) {
                Flow.Subscription subscription = new Flow.Subscription() {

                    @Override
                    public void request(long n) {
                        subscriber.onNext("hello world");
                    }

                    @Override
                    public void cancel() {


                    }
                };
                subscriber.onSubscribe(subscription);
            }
        };

        Flow.Subscriber<String> subscriber = new Flow.Subscriber<>() {
            Flow.Subscription subscription;

            @Override
            public void onSubscribe(Flow.Subscription subscription) {
                this.subscription = subscription;
                System.out.println("开始订阅");
                subscription.request(1);
            }

            @Override
            public void onNext(String item) {
                System.out.println("收到数据：" + item);
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("消息有误");
            }

            @Override
            public void onComplete() {
                System.out.println("数据接受完毕");
            }
        };
        Processor processor = new Processor();

        processor.subscribe(subscriber);
        publisher.subscribe(processor);

        Thread.sleep(2000);

    }
}
